﻿using GateWayService.Mq;
using IotDeviceToolHepler.Device;
using Microsoft.EntityFrameworkCore;
using Models.Common;
using Models.Constant;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utils_Base;
using Utils_ORM;
using Utils_ORM.MySql_IotWork;

namespace GateWayService.Device
{
    public class ServiceJiDianQi
    {
        DataEFContext ef = new DataEFContext();
        //public static DataTable getJiDianQiTaskByGuid(Guid djtGuid)
        //{
        //    string sql = "select top 1 * from iot_device_jidianqi_Task where djt_guid='" + djtGuid + "' ";
        //    return DBUtility.SqlSugarMySqlHelper.GetDataTable(sql);
        //}

        /// <summary>
        /// 更改继电器状态
        /// </summary>
        /// <param name="reqIotModel"></param>
        /// <param name="loginUserInfo"></param>
        public void changeJiDianQiState(HttpReqModel reqIotModel, ClientLoginUserInfo loginUserInfo)
        {
            string sqlwhere = " and 1=2 ";
            if (!string.IsNullOrEmpty(reqIotModel.guid))
            {
                sqlwhere = " and dj_guid='" + reqIotModel.guid + "'";
            }
            iot_device_jidianqi iot_Device_Jidianqi = new DataEFContext().iot_device_jidianqi.Where(c => c.dj_guid == reqIotModel.guid).FirstOrDefault();//
            string sql = "select * from iot_device_jidianqi inner join iot_device_gateway on gw_guid=dj_gw_guid where 1=1 " + sqlwhere + " order by dj_id desc";
            DataTable dt = SqlSugarMySqlHelper.GetDataTable(sql);
            foreach (DataRow row in dt.Rows)
            {
                iot_Device_Jidianqi.dj_live_state = 4;
                new ServiceJiDianQi().sendCommandJiDianQi(loginUserInfo, iot_Device_Jidianqi, JiDianQiCommandEnum.JiDianQi_CHECK_STATE);

            }

        }



        //回调获获继电器状态,为了避免误差，查状态和执行，都返回了 当前开关状态
        public void callBack_updateJiDianStatus(int status, string msg, CommandLogModel commandLogModel)
        {
            // DataTable dt = getJiDianQiTaskByGuid(Guid.Parse(jiDianQiApiModel.guid));
            string commandKey = ServiceDeviceCommand.getDeviceCommandKey(commandLogModel.d_guid.ToString(), msg);

            int logStatus = (int)Device_Command_Log.callBackError;
            if (status == (int)Jidianqi_Live_State.open || status == (int)Jidianqi_Live_State.close)
            {
                logStatus = (int)Device_Command_Log.callBackSuccess;
            }
            string sql = "update  iot_device_command_log set dcl_status=" + logStatus + ",dcl_status_remark='MQ返回处理完成',dcl_return_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',dcl_return_msg='" + msg + "' where dcl_guid='" + commandLogModel.guid + "' ";
            SqlSugarMySqlHelper.ExecuteCommand(sql);

            //  string sql = "update  iot_device_jidianqi_Task set djt_status=" + status + ",djt_return_time='"+System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+"',djt_return_msg='" + msg + "' where djt_guid='" + Guid.Parse(jiDianQiApiModel.guid) + "' ";
            //  DBUtility.SqlSugarMySqlHelper.ExecuteCommand(sql);

            int dj_live_state = 0;
            int d_live_state = 0;

            if (commandKey == JiDianQiCommandEnum.JiDianQi_RETURN_OPEN || commandKey == Jidianqi_Live_State.open.ToString() || commandLogModel.key == Jidianqi_Live_State.open.ToString())
            {
                dj_live_state = (int)Jidianqi_Live_State.open;
                d_live_state = (int)Device_State.normal;

            }
            else if (commandKey == JiDianQiCommandEnum.JiDianQi_RETURN_CLOSE || commandKey == Jidianqi_Live_State.close.ToString() || commandLogModel.key == Jidianqi_Live_State.close.ToString())
            {
                dj_live_state = (int)Jidianqi_Live_State.close;
                d_live_state = (int)Device_State.normal;

            }
            else
            {
                dj_live_state = (int)Jidianqi_Live_State.error;
                d_live_state = (int)Device_State.error;
            }

            sql = "update iot_device_jidianqi set dj_live_state_set_return_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',dj_live_state=" + dj_live_state + ",dj_live_state_remark ='" + msg + "'    where dj_guid='" + Guid.Parse(commandLogModel.table_guid) + "' ";
            new SqlSugarMySqlHelper().Db.Ado.ExecuteCommand(sql);


            //更新设备状态，设备状态
            sql = "update iot_device set d_live_state=" + d_live_state + ",d_live_state_set_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',d_live_sate_remark ='" + msg + "'  where d_guid='" + commandLogModel.d_guid + "' ";
            new SqlSugarMySqlHelper().Db.Ado.ExecuteCommand(sql);


        }
        /// <summary>
        /// 判断是否需要重新获取设备状态，比如离线很久了，重新上线
        /// </summary>
        /// <param name="dt"></param>
        public void resetDeviceStatus(DataTable dt, Model_GateWay reqIotModel)
        {
            try
            {

                //获取继电器状态
                string sqljidainqi = "select dj_guid from iot_device_jidianqi where dj_gw_guid='" + dt.Rows[0]["gw_guid"] + "'";
                DataTable dtjidainqi = new SqlSugarMySqlHelper().Db.Ado.GetDataTable(sqljidainqi);
                foreach (DataRow dataRow in dtjidainqi.Rows)
                {
                    HttpReqModel reqIotModel2 = new HttpReqModel();
                    reqIotModel2.guid = dataRow["dj_guid"].ToString();
                    new ServiceJiDianQi().changeJiDianQiState(reqIotModel2, new ClientLoginUserInfo());
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        /// <summary>
        /// 打开或关闭继电器
        /// </summary>
        /// <param name="clientLoginUserInfo"></param>
        /// <param name="iot_Device_Jidianqi"></param>
        /// <param name="commandKey"></param>
        public void sendCommandJiDianQi(ClientLoginUserInfo clientLoginUserInfo, iot_device_jidianqi iot_Device_Jidianqi, string commandKey)
        {
            // string command = ServiceDeviceCommand.getDeviceCommandValue(iot_Device_Jidianqi.dj_d_guid, commandKey);
            iot_device_command iot_Device_Command = ServiceDeviceCommand.getDeviceCommand(iot_Device.d_guid, commandKey);
            string dcl_guid = Guid.NewGuid().ToString();
            string djt_guid = Guid.NewGuid().ToString();
            //关

            //状态，会在收到设备执行回调的时候，重新更新状态确认   //dj_live_state='" + iot_Device_Jidianqi.dj_live_state + "',
            string sql = "update iot_device_jidianqi set dj_live_state_set_time='" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where dj_guid='" + iot_Device_Jidianqi.dj_guid + "'";
            SqlSugarMySqlHelper.ExecuteCommand(sql);

            iot_device_gateway iot_Device_Gateway = new DataEFContext().iot_device_gateway.Where(c => c.gw_guid == iot_Device_Jidianqi.dj_gw_guid).FirstOrDefault();
            //写日志
            CommandLogModel commandLogModel = new CommandLogModel();
            commandLogModel.guid = Guid.NewGuid();
            commandLogModel.d_guid = Guid.Parse(iot_Device_Jidianqi.dj_d_guid);
            commandLogModel.content = command;
            commandLogModel.key = commandKey;
            commandLogModel.status_remark = "待处理";
            commandLogModel.status = 1;
            commandLogModel.mqevent = MQEventEnum.Device_Jidianqi;
            commandLogModel.deviceId = iot_Device_Gateway.gw_deviceId;// dt.Rows[0]["gw_deviceId"].ToString();
            commandLogModel.deviceGuid = iot_Device_Gateway.gw_d_guid;
            //commandLogModel.table_guid = iot_Device_Jidianqi.dj_guid;// dt.Rows[0]["dj_guid"].ToString();
            commandLogModel.local_port = iot_Device_Jidianqi.dj_local_port;// dt.Rows[0]["dj_local_port"].ToString();
            commandLogModel.local_ip = iot_Device_Jidianqi.dj_local_ip;// dt.Rows[0]["dj_local_ip"].ToString();
                                                                       // commandLogModel.gpio_position = iot_Device_Jidianqi.dj_gpio_position;// dt.Rows[0]["dj_gpio_position"].ToString();
            commandLogModel.agreementType = iot_Device_Jidianqi.dj_agreement_type;// dt.Rows[0]["dj_agreement_type"].ToString();
            commandLogModel.device_remark = iot_Device_Jidianqi.dj_machine_name;// dt.Rows[0]["dj_machine_name"].ToString();
            commandLogModel.user_guid = clientLoginUserInfo.user_guid;
            commandLogModel.user_name = clientLoginUserInfo.user_name;
            commandLogModel.user_remote_ip = clientLoginUserInfo.login_ip;
            ServiceDeviceCommand.writeCommandLog(commandLogModel);


            // new ServiceJiDianQi().sendMQ_JiDianQi(commandLogModel);
            Task tasksendMsg = new ServiceSendMQ().sendMsgToDeviceCommand(commandLogModel);
        }


        /// <summary>
        /// 查询继电器状态
        /// </summary>
        public int getJiDianQiState(string deviceGuid)
        {
            iot_device_jidianqi model = ef.iot_device_jidianqi.Where(c => c.dj_d_guid == deviceGuid).FirstOrDefault();
            if (model != null)
            {
                return (int)model.dj_live_state;
            }
            return (int)Jidianqi_Live_State.error;
        }

        public void DeviceReciveJiDianQiCommand(MQReqModel<CommandLogModel> mQReqModel)
        {
            #region


            Console.WriteLine("toWork时间：" + DateTime.Now);
            try
            {

                Console.WriteLine("初始定时检测");
                Console.WriteLine("待执行指令:" + JsonConvert.SerializeObject(mQReqModel.data));
                if (mQReqModel.data.dcl_agreement_type == "gpio")
                {
                    //gpio引强断电器
                    Console.WriteLine("gpio 执行");
                    if (mQReqModel.data.content == Jidianqi_Live_State.check_state.ToString())
                    {

                        //查状态
                        string check_state = new OrangePiGpio().GetGpioOutputMode(int.Parse(mQReqModel.data.dcl_gpio_position));
                        //MQReqModel<CommandLogModel> mQReqModel = new MQReqModel<CommandLogModel>();
                        //mQReqModel.respEvent = MQEventEnum.Device_Jidianqi;// "miniServer_jidianqi";
                        //mQReqModel.respCode = JiDianQiCommandEnum.getReturnStatus(check_state).ToString();
                        mQReqModel.respCode = ((int)Enum.Parse(typeof(Jidianqi_Live_State), check_state)).ToString();
                        mQReqModel.respMsg = check_state;//open/close
                        //mQReqModel.deviceId = UtilsMachineInfo.getMachineId();
                        //mQReqModel.data = getMQReqModel.data;
                        //mQReqModel.guid = getMQReqModel.guid;
                        new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));

                        return;
                    }
                    else
                    {
                        //执行开关
                        string result = new OrangePiGpio().SetGpioOutputMode(mQReqModel.data.content, int.Parse(mQReqModel.data.dcl_gpio_position));
                        //MQReqModel<CommandLogModel> mQReqModel = new MQReqModel<CommandLogModel>();
                        //mQReqModel.respEvent = MQEventEnum.Device_Jidianqi;// "miniServer_jidianqi";
                        // mQReqModel.respCode = JiDianQiCommandEnum.getReturnStatus(result).ToString();
                        mQReqModel.respCode = ((int)Enum.Parse(typeof(Jidianqi_Live_State), result)).ToString();
                        mQReqModel.respMsg = result;
                        //mQReqModel.deviceId = UtilsMachineInfo.getMachineId();
                        //mQReqModel.data = getMQReqModel.data;
                        //mQReqModel.guid = getMQReqModel.guid;
                        new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                        //FileHelper.deviceServer_WriteMessageAppend("payMsg 消费 jidianqi 55555555555555 " + JsonConvert.SerializeObject(mQReqModel));
                        return;
                    }
                    // Console.WriteLine("等待返回值");

                }
                else if (mQReqModel.data.dcl_agreement_type == "orangepii96-gpio")
                {
                    //gpio引强断电器
                    Console.WriteLine("orangepii96-gpio 执行");
                    ServiceJidianQiCommandByOrangePiI96ServiceGpio.write(mQReqModel.data.dcl_gpio_position, mQReqModel.data.content);

                    Console.WriteLine("等待返回值");

                    //MQReqModel<CommandLogModel> mQReqModel = new MQReqModel<CommandLogModel>();
                    //mQReqModel.respEvent = MQEventEnum.Device_Jidianqi_Return;// "miniServer_jidianqi";
                    mQReqModel.respCode = ((int)MQEventEnum.JiDianQI_Event_State.Normal).ToString();
                    mQReqModel.respMsg = MQEventEnum.Event_State_OK;
                    //mQReqModel.deviceId = UtilsMachineInfo.getMachineId();
                    //mQReqModel.data = commandLogModel;
                    //mQReqModel.guid = Guid.NewGuid().ToString();
                    new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                    return;

                }
                else
                {
                    //FileHelper.deviceServer_WriteMessageAppend("payMsg 消费 jidianqi 666666666 ");

                    if (ServiceJiDianQICommandByWifi.sendAndReceiveToServer(mQReqModel))
                    { //wifi继电器
                        Console.WriteLine("wifi socket 执行");
                        //FileHelper.deviceServer_WriteMessageAppend(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString() + " sendAndReceiveToServer返回执行结果");
                        //Thread.Sleep(reqJiDianQiApiModel.keepTime);
                        Thread.Sleep(1000);//等待返回值

                        Console.WriteLine("等待返回值");
                        ReceiveCallbackModel receiveCallbackModel = ServiceJiDianQICommandByWifi.receiveCallbackModels.Where(c => c.guid == mQReqModel.data.dcl_guid.ToString()).FirstOrDefault();
                        if (receiveCallbackModel != null)
                        {
                            //MQReqModel<CommandLogModel> mQReqModel = new MQReqModel<CommandLogModel>();
                            //mQReqModel.respEvent = MQEventEnum.Device_Jidianqi_Return;// "miniServer_jidianqi";
                            mQReqModel.respCode = "2";
                            mQReqModel.respMsg = receiveCallbackModel.ReceiveContent.Trim();
                            mQReqModel.deviceId = UtilsMachineInfo.getMachineId();
                            //mQReqModel.data = commandLogModel;
                            //mQReqModel.guid = Guid.NewGuid().ToString();
                            new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));

                            //删除缓存
                            ServiceJiDianQICommandByWifi.receiveCallbackModels.Remove(receiveCallbackModel);
                            return;
                        }

                    }

                }
                if (true)
                {

                    //MQReqModel<CommandLogModel> mQReqModel = new MQReqModel<CommandLogModel>();
                    //mQReqModel.respEvent = MQEventEnum.Device_Jidianqi_Return;
                    mQReqModel.respCode = ((int)MQEventEnum.JiDianQI_Event_State.Error).ToString();
                    mQReqModel.respMsg = GpioCommandEnum.RETURN_ERROR;
                    // mQReqModel.deviceId = UtilsMachineInfo.getMachineId();
                    //mQReqModel.data = commandLogModel;
                    //mQReqModel.guid = Guid.NewGuid().ToString();
                    new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                }

            }
            catch (Exception ex)
            {

                //MQReqModel<CommandLogModel> mQReqModel = new MQReqModel<CommandLogModel>();
                //mQReqModel.respEvent = MQEventEnum.Device_Jidianqi_Return;
                mQReqModel.respCode = ((int)MQEventEnum.JiDianQI_Event_State.Error).ToString();
                mQReqModel.respMsg = GpioCommandEnum.RETURN_ERROR;
                //mQReqModel.deviceId = UtilsMachineInfo.getMachineId();
                //mQReqModel.data = commandLogModel;
                // mQReqModel.guid = Guid.NewGuid().ToString();
                new ServiceRabbitMQ_DeviceHelper().sendMsg(JsonConvert.SerializeObject(mQReqModel));
                Console.WriteLine(DateTime.Now.ToString() + ex);
                new UtilsFileHelper().log_WriteMessageAppend("error", ex.ToString());
            }
            #endregion
        }


    }
}
